import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/*
 * 基于Socket的SMTP邮件发送客户端
 */
public class SMTPClient {
    public static void main(String[] args) {
        // 消息发送与接收方初始化
        String sendUserName = "m13337046103@163.com";
        String sendUserPassword = "ch78661697300000";
        String receiveUserName = "19281121@bjtu.edu.cn";
        // Base64编码
        String userNameBase64 = Base64Util_cc.encodeBase64(sendUserName.getBytes(StandardCharsets.UTF_8));
        String userPasswordBase64 = Base64Util_cc.encodeBase64(sendUserPassword.getBytes(StandardCharsets.UTF_8));

        try {
            // 远程连接smtp.163.com
            Socket socket = new Socket("smtp.163.com", 25);
            // 输入流
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            // 输出流
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream, true);
            // 输出连接信息
            System.out.println(bufferedReader.readLine());
            // 向服务器发送邮件
            // helo
            printWriter.println("helo 13337046103");
            System.out.println(bufferedReader.readLine());
            // auth login
            printWriter.println("auth login");
            System.out.println(bufferedReader.readLine());
            printWriter.println(userNameBase64);
            System.out.println(bufferedReader.readLine());
            printWriter.println(userPasswordBase64);
            System.out.println(bufferedReader.readLine());
            // set "mail from" and "rcpt to"
            printWriter.println("mail from:<" + sendUserName + ">");
            System.out.println(bufferedReader.readLine());
            printWriter.println("rcpt to:<" + receiveUserName + ">");
            System.out.println(bufferedReader.readLine());
            // set "data"
            printWriter.println("data");
            System.out.println(bufferedReader.readLine());
            // 邮件正文部分
            printWriter.println("subject:testMail");
            printWriter.println("from:" + sendUserName);
            printWriter.println("to:" + receiveUserName);
            printWriter.println("Content-Type: text/plain;charset=utf-8");
            printWriter.println();
            printWriter.println("这是一封测试邮件。");
            printWriter.println(".");
            printWriter.println();
            System.out.println(bufferedReader.readLine());
            // 发送完毕中断连接
            printWriter.println("rset");
            System.out.println(bufferedReader.readLine());
            printWriter.println("quit");
            System.out.println(bufferedReader.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
